package com.xy.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xxy
 * @date 2022/1/7 14:50
 */
@RestController
@RequestMapping("use-redis-local-lock")
@Slf4j
public class UseRedisLocalLockController {

    private final StringRedisTemplate stringRedisTemplate;

    public UseRedisLocalLockController(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @GetMapping("test-redis-local-lock")
    public Object testUseRedisLocalLock() {

        // 加本地锁
        synchronized (this) {
            // 从缓存中查数据
            String dataListCache = stringRedisTemplate.opsForValue().get("dataList");
            if (StringUtils.isNotBlank(dataListCache)) {
                // 如果缓存不为空，序列化为实列对象，返回结果
                JSON.parseObject(dataListCache, new TypeReference<List<String>>() {
                });
                return dataListCache;
            }
            // 如果缓存中没有数据，查询数据库
            log.info("the cache is empty!");
            List<String> dbList = dataList();
            // 将数据库数据序列化json字符串
            dataListCache = JSON.toJSONString(dbList);
            // 将序列化的结果放入缓存
            stringRedisTemplate.opsForValue().set("dataList", dataListCache, 10, TimeUnit.SECONDS);
            return dbList;
        }
    }


    private List<String> dataList() {
        List<String> dataList = new ArrayList<>();
        String[] data = {"a", "b", "c"};
        List<String> list = Arrays.asList(data);
        dataList.addAll(list);
        return dataList;
    }


}
